import cv2
import numpy as np

def mathc_img(image,Target,value):
    img_rgb = cv2.imread(image)
    img_gray = cv2.cvtColor(img_rgb, cv2.THRESH_TOZERO)    
    template = cv2.imread(Target,0)    
    #template_tozero = cv2.cvtColor(template, cv2.THRESH_TOZERO)   
    w, h = template.shape[::-1]

    #img_tar = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)        
    
    #二值化处理，低于阈值的像素点灰度值置为0；高于阈值的值置为参数3
    #ret,thresh1 = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)
    #cv2.imshow('BINARY',thresh1)
    
    #大于阈值的像素点灰度值置为0；小于阈值置为参数3
    #ret,thresh2 = cv2.threshold(img_gray,127,200,cv2.THRESH_BINARY_INV)
    #cv2.imshow('BINARY_INV',thresh2)
    
    #小于阈值的像素点灰度值不变，大于阈值的像素点置为该阈值
    #ret,thresh3 = cv2.threshold(img_gray,127,255,cv2.THRESH_TRUNC)
    #cv2.imshow('TRUNC',thresh3)
    
    #小于阈值的像素点灰度值不变，大于阈值的像素点置为0,其中参数3任取
    #ret,thresh4 = cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO)    
    #cv2.imshow('BINARY_TOZERO',thresh4)
    
    
    #大于阈值的像素点灰度值不变，小于阈值的像素点置为0,其中参数3任取
    #ret,thresh5 = cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO_INV)
    #cv2.imshow('BINARY_TOZERO_INV',thresh5)

    #res = cv2.matchTemplate(thresh4,thresh5,cv2.TM_CCOEFF_NORMED)
    res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
    threshold = value
    loc = np.where( res >= threshold)    
    for pt in zip(*loc[::-1]):
        right_bottom = (pt[0] + w, pt[1] + h)
        cv2.rectangle(img_rgb, pt, right_bottom, (0, 0, 255), 2)
        #cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (7,249,151), 2)   
    
    cv2.imshow('Detected',img_rgb)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == '__main__':
    image=("F:\\ml\\moban\\test2.PNG")
    Target=('F:\\ml\\moban\\scene.PNG')
    value=0.8
    mathc_img(image,Target,value)